package com.mcptt.http.operator.addr;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

import com.cloudptt.api.product.func.addr.IAddrDefaultOp;
import com.cloudptt.api.product.log.Log;
import com.mcptt.comm.CommonFunc;
import com.mcptt.config.local.SysConfig;
import com.mcptt.db.DBAdapter;
import com.mcptt.db.model.GroupInfo;
import com.mcptt.db.model.UserInfo;
import com.mcptt.http.operator.IHttpAddrOpCb;
import com.mcptt.http.operator.OkHttpUtils;

import android.os.Handler;
import android.os.Message;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class AddressLoader implements Callback{
	private static final String HTTP_KEY = "http://";;
	private static final String Sub_Url = ":8084/portal/Address.xml";
//	private static final String Sub_Url = ":8380/ue/Address.xml";;
	private static final int ConnectionTimeout = 30 * 1000;
	private static final int SoTimeout = 30 * 1000;
	protected final static int OP_SUC = 0;
	protected final static int OP_FAILED = 1;
	private String svrIp = null;
	private DBAdapter dbOperator = null;
	protected IHttpAddrOpCb callback = null;
	private IAddrDefaultOp defaultOp = null;

	public AddressLoader(SysConfig config, DBAdapter dbOperator, IHttpAddrOpCb callback, IAddrDefaultOp defaultOp)
	{
		this.svrIp = config.getBootStrapSvr().getServerIp();
		this.dbOperator = dbOperator;
		this.callback = callback;
		this.defaultOp = defaultOp;
	}

	public void load() {
		final String url = HTTP_KEY + svrIp + Sub_Url;


		new Thread(new Runnable(){
			@Override
			public void run() 
			{
				try {
//					doHttpGet(url);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}

	private void doHttpGet(String url) throws Exception
	{
		Log.debug(getClass(), "doHttpGet url = " + url);
		OkHttpUtils.getInstance().doGet(url, this);
	}

	private void sendOpResultMsg(boolean isSuc)
	{
		if(isSuc)
		{
			Message msg = handler.obtainMessage(OP_SUC);
			msg.sendToTarget();
		}
		else
		{
			Message msg = handler.obtainMessage(OP_FAILED);
			msg.sendToTarget();
		}
	}

	protected Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch(msg.what)
			{
			case OP_SUC:
				if(callback != null)
				{
					callback.onAddrUptResult(true);
				}
				break;
			case OP_FAILED:
				if(callback != null)
				{
					callback.onAddrUptResult(false);
				}
				break;
			}
		}
	};

	@Override
	public void onFailure(Call arg0, IOException arg1) {
		// TODO Auto-generated method stub
		sendOpResultMsg(false);
	}

	@Override
	public void onResponse(Call arg0, Response response) throws IOException {
		// TODO Auto-generated method stub
		if(response == null)
		{
			sendOpResultMsg(false);
			return;
		}
		dbOperator.deleteAllGroupInfo();
		dbOperator.deleteAllUserInfo();

		Log.debug(getClass(), "onResponse isSuccessful = " + response.isSuccessful());
		if(response.isSuccessful())
		{
			InputStream instreams = response.body().byteStream();
			String content = CommonFunc.convertStreamToString(instreams);
			Log.debug(getClass(), "onResponse content = " + content);
			try 
			{
				List<GroupInfo> groupList = AddressParser.parseAddressStr(content);
				Log.debug(getClass(), "onResponse groupList = " + groupList);
				int i= 0;
				for(Iterator<GroupInfo> itor = groupList.iterator();itor.hasNext();)
				{
					GroupInfo groupInfo = itor.next();
					if(i == 0)
					{
						groupInfo.setIsAffiliation(true);
						defaultOp.setDefaultGroupInfo(groupInfo);
					}
					else
					{
						groupInfo.setIsAffiliation(false);
					}
					i++;
					if(groupInfo != null)
					{
						dbOperator.addGroupInfo(groupInfo);
						List<UserInfo> userList = groupInfo.getMemberList();

						Log.debug(getClass(), "onResponse userList = " + userList);
						for(Iterator<UserInfo> uItor = userList.iterator();uItor.hasNext();)
						{
							UserInfo info = uItor.next();
							if(info != null)
							{
								dbOperator.addUserInfo(info);
							}
						}
					}
				}
				
				if(groupList != null
						&& groupList.size() > 0)
				{
					sendOpResultMsg(true);
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}

			sendOpResultMsg(false);
		}
		else
		{
			sendOpResultMsg(false);
			//	    notifyFailed(parserCallback,"readFromSvr code = " + code);
		}
	}

}
